package com.video.web.controller.app;

import com.alibaba.fastjson2.JSONObject;
import com.video.common.core.controller.BaseController;
import com.video.common.core.domain.AjaxResult;
import com.video.common.core.page.TableDataInfo;
import com.video.common.exception.ServiceException;
import com.video.common.utils.StringUtils;
import com.video.video.domain.DGoods;
import com.video.video.domain.DUser;
import com.video.video.domain.DWthdrawalRecord;
import com.video.video.domain.app.dto.AppOrderDto;
import com.video.video.domain.app.dto.DOrderRecordDto;
import com.video.video.domain.app.dto.SubgiftVo;
import com.video.video.domain.dto.DSubgiftRecordDto;
import com.video.video.domain.vo.DSubgiftRecordQuery;
import com.video.video.service.IDGoodsService;
import com.video.video.service.IDOrderRecordService;
import com.video.video.service.IDSubgiftRecordService;
import com.video.video.service.IDUserService;
import com.video.video.service.IDWthdrawalRecordService;
import com.video.video.service.impl.DGoodsServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.math.BigDecimal;
import java.util.List;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Api(tags = "订单")
@RestController
@RequestMapping("/appo/order")
public class AppOrderController extends BaseController {
  private static final Logger log = LoggerFactory.getLogger(AppOrderController.class);
  @Resource
  private IDOrderRecordService orderRecordService;
  @Resource
  private IDSubgiftRecordService subgiftRecordService;//转赠记录
  @Autowired
  private IDUserService idUserService;
  @Autowired
  private IDWthdrawalRecordService dWthdrawalRecordService;
  @Autowired
  private IDGoodsService dGoodsService;

  @ApiOperation(value = "生成订单")
  @PostMapping("/createOrder")
  public AjaxResult createOrder(@Validated AppOrderDto orderDto) {
    logger.info("生成订单:" + JSONObject.toJSONString(orderDto));
    String userId = String.valueOf(getLoginUser().getUserId());
    orderDto.setUserId(userId);
    if (StringUtils.isEmpty(orderDto.getUserId())) {
      throw new ServiceException("会员Id不能为空", 10077);
    }

    if (StringUtils.isEmpty(orderDto.getGoodId())) {
      throw new ServiceException("商品Id不能为空", 10079);
    }

    if (orderDto.getSellPrice() == null) {
      throw new ServiceException("商品价格不能为空", 10081);
    }
    orderRecordService.insertAppOrdery(orderDto);

    return AjaxResult.success("购买成功成功");
  }


  @ApiOperation(value = "获取订单列表-支持分页")
  @GetMapping("/getOrder")
  public TableDataInfo getOrder() {
    String userId = String.valueOf(getLoginUser().getUserId());
    startPage();
    List<DOrderRecordDto> list = orderRecordService.selectDOrderRecordDtoList(userId);
    return getDataTable(list);
  }

  /**
   * 转赠 逻辑如下：
   *   先从转赠送的人 余额中扣除  余额不够再从赠送金额中 扣除
   *     不做对应项的扣除  既： 充值金额 + 赠送金额  先从 余额中扣
   *
   * @param vo
   * @return
   */
  @ApiOperation(value = "合伙人-转赠")
  @PostMapping("/subgift")
  public AjaxResult subgift(@Validated SubgiftVo vo) {
    if(org.apache.commons.lang3.StringUtils.isBlank(vo.getHid())){
      throw new ServiceException("合伙人id不能为空");
    }
    String userId = String.valueOf(getLoginUser().getUserId());
    if(!vo.getHid().equals(userId)){
      throw new ServiceException("合伙人身份不匹配,请核对后再操作");
    }
    if(org.apache.commons.lang3.StringUtils.isBlank(vo.getUid())){
      throw new ServiceException("会员id不能为空");
    }

    //判断会员是否存在
    DUser hehuoren= idUserService.selectDUserById(vo.getHid());
    if(hehuoren == null){
      throw new ServiceException("合伙人不存在");
    }

    if(!hehuoren.getLevel().equals("5")){
      throw new ServiceException("当前会员非合伙人,不能进行转赠");
    }

    DUser huiyuan= idUserService.selectDUserById(vo.getUid());
    if(huiyuan == null){
      throw new ServiceException("会员不存在");
    }
    //判断当前充值金额与合伙人钱包余额
    //判断合伙人 余额 + 赠送金额  是否 < 需充值金额 + 需赠送金额
    if(vo.getAmount() == null){
       vo.setAmount(new BigDecimal("0.00"));
    }
    if(vo.getGiveAmount() == null){
       vo.setGiveAmount(new BigDecimal("0.00"));
    }

    BigDecimal hehuorenMoney = hehuoren.getBalance().add(hehuoren.getGiveBalance());
    BigDecimal giveMoney = vo.getAmount().add(vo.getGiveAmount());

    if(hehuorenMoney.compareTo(giveMoney) < 0){
      throw new ServiceException("合伙人余额不足");
    }

    subgiftRecordService.insertAPPSubgiftRecord(vo);
    return AjaxResult.success("转赠成功");
  }

  @ApiOperation(value = "合伙人-转赠记录列表-支持分页")
  @GetMapping("/getSubgiftOrder")
  public TableDataInfo getSubgiftOrder() {
    String userId = String.valueOf(getLoginUser().getUserId());
    DSubgiftRecordQuery query=new DSubgiftRecordQuery();
    query.setHid(userId);
    startPage();
    List<DSubgiftRecordDto> list = subgiftRecordService.selectDSubgiftRecordList(query);
    return getDataTable(list);
  }

  @ApiOperation(value = "提现申请")
  @PostMapping("/applyForWithdrawal")
  public AjaxResult applyForWithdrawal(@RequestBody DWthdrawalRecord dWthdrawalRecord) {
    logger.info("提现申请:" + JSONObject.toJSONString(dWthdrawalRecord));
    String userId = String.valueOf(getLoginUser().getUserId());
    if(!userId.equals(dWthdrawalRecord.getUid())){
      throw new ServiceException("申请提现会员ID有误,请核对后再申请");
    }
    //判断会员是否存在
    DUser huiyuan= idUserService.selectDUserById(dWthdrawalRecord.getUid());
    if(huiyuan == null){
      throw new ServiceException("会员不存在");
    }
    if(huiyuan.getLevel().equals("5") ){
      throw new ServiceException("合伙人不能进行提现");
    }

    if(huiyuan.getCommissionBalance().compareTo(dWthdrawalRecord.getAmount()) ==-1 ){
      throw new ServiceException("提现金额大于返佣余额");
    }
    return toAjax(dWthdrawalRecordService.insertDWthdrawalRecord(dWthdrawalRecord));
  }

  @ApiOperation(value = "修改商品下载状态")
  @GetMapping("/updateGoodDownloadFlg")
  public AjaxResult updateGoodDownloadFlg(String goodId) {
    log.info("修改商品下载状态-goodId:"+goodId);
    String userId = String.valueOf(getLoginUser().getUserId());
    DGoods goods= dGoodsService.selectDGoodsById(goodId);
    if(goods == null){
      throw new ServiceException("商品不存在");
    }
    if(!userId.equals(goods.getBuyerId())){
      throw new ServiceException("当前人非购买人");
    }
    DGoods updateGood=new DGoods();
    updateGood.setId(goodId);
    updateGood.setDownloadFlg("2");
    int flg=dGoodsService.updateDGoods(updateGood);
    log.info("修改商品下载状态结果:"+flg);
    return toAjax(flg);
  }
}
